package utils

import (
	"strings"

	"github.com/getkin/kin-openapi/openapi3"
)

func FindInPaths(paths openapi3.Paths, reqUrl string) (*openapi3.PathItem, map[string]string) {
	path := paths.Find(reqUrl)
	if path != nil {
		return path, nil
	}
	for name, defP := range paths {
		vars, ok := matchUrlWithPars(reqUrl, name)
		if ok {
			return defP, vars
		}
	}
	return nil, nil
}

func matchUrlWithPars(reqU, defU string) (vars map[string]string, ok bool) {
	var indexInReq, indexInDef int
	var varName, varValue string
	vars = make(map[string]string)
	for {
		firstLB := strings.Index(defU[indexInDef:], "{")
		if firstLB >= 0 {
			if indexInReq+firstLB > len(reqU) {
				return
			}
			if reqU[indexInReq:indexInReq+firstLB] == defU[indexInDef:indexInDef+firstLB] {
				//continue

				firstRB := strings.Index(defU[indexInDef+firstLB:], "}")
				if firstRB > 0 {
					varName = strings.TrimSpace(defU[indexInDef+firstLB+1 : indexInDef+firstLB+firstRB])
					indexInDef += firstLB + firstRB + 1
				}
				if indexInReq+firstLB < len(reqU) {

					firstSpliter := strings.Index(reqU[indexInReq+firstLB:], "/")
					if firstSpliter < 0 {
						firstSpliter = len(reqU) - firstLB - indexInReq
					}
					// if firstSpliter >= 0 {
					varValue = reqU[indexInReq+firstLB : indexInReq+firstLB+firstSpliter]
					indexInReq += firstSpliter
					// }
				}
				indexInReq += firstLB
				vars[varName] = varValue
				if indexInReq >= len(reqU) {
					ok = indexInDef >= len(defU)
					return
				} else if indexInDef >= len(defU) {
					return
				}
			} else {
				return
			}
		} else {
			ok = defU[indexInDef:] == reqU[indexInReq:]
			return
		}
	}

}
